package com.itheima.service.impl;


import com.itheima.dao.UserMapper;
import com.itheima.pojo.User;
import com.itheima.service.LoginService;
import com.itheima.service.UserService;
import com.itheima.utils.*;
import com.itheima.vo.UserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author kehaonan
 * @version 1.0
 * @date 2020/7/10 13:53
 */
@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private UserMapper userDao;
    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private HttpServletResponse response;
    @Autowired
    private IdWorker idWorker;
    @Override
    public String login(UserVO userVO, HttpServletRequest request) {
        User user = new User();
        user.setUserName(userVO.getUserName());
        user.setPassWord(MD5Utils.md5(userVO.getPassWord()));
        user = userDao.selectOne(user);
        if (user==null || !"1".equals(String.valueOf(user.getStatus()))){
            return null;
        }
        //获取Ip地址
        String realIp = IpUtils.getRealIp(request);
        //获取访问的浏览器
        Map<String, String> osAndBrowserInfo = IpUtils.getOsAndBrowserInfo(request);
        String browser = osAndBrowserInfo.get("BROWSER");
        String loginRedisKey = "user_"+user.getUid();
        redisTemplate.boundHashOps(loginRedisKey).put("username",user.getUserName());
        redisTemplate.boundHashOps(loginRedisKey).put("password",user.getPassWord());
        redisTemplate.boundHashOps(loginRedisKey).put("uid",user.getUid());
        redisTemplate.expire(loginRedisKey,30, TimeUnit.MINUTES);
        user.setLastLoginTime(DateUtils.getNowTime());
        user.setLastLoginIp(realIp);
        user.setLoginCount(user.getLoginCount()+1);
        user.setBrowser(browser);
        userDao.updateByPrimaryKeySelective(user);
        Cookie cookie =null;
        //设置用户登录信息
        cookie = new Cookie("token",loginRedisKey);
        cookie.setPath("/");
        cookie.setMaxAge(24 * 60 * 60);
        response.addCookie(cookie);
        //设置用户Id
        cookie = new Cookie("userId",user.getUid());
        cookie.setPath("/");
        cookie.setMaxAge(24 * 60 * 60);
        response.addCookie(cookie);

        return loginRedisKey;
    }

    @Override
    @Transactional
    public Boolean register(UserVO userVO, HttpServletRequest request) {
        User user = new User();
        user.setUserName(userVO.getUserName());
        //根据用户名查找这个用户名是否已经注册
        user = userDao.selectOne(user);
        if (user != null){
            return false;
        }
        user=new User();
        user.setUid(String.valueOf(idWorker.nextId()));
        user.setUserName(userVO.getUserName());
        //密码用MD5加密

        user.setPassWord(MD5Utils.md5(userVO.getPassWord()));
        user.setGender(Integer.parseInt(userVO.getGender()));
        user.setAvatar(userVO.getAvatar());

        user.setEmail(userVO.getEmail());
        user.setBirthday(userVO.getBirthday());

        user.setMobile(userVO.getMobile());
        //随机生成一个验证码4位
        Integer validateCode = ValidateCodeUtils.generateValidateCode(4);
        user.setValidCode(String.valueOf(validateCode));
        user.setSummary(userVO.getSummary());
        user.setLoginCount((int) 0L);
        //1是激活0是未激活
        user.setStatus(0);
        user.setCreateTime(DateUtils.getNowTime());
        user.setUpdateTime(DateUtils.getNowTime());
        user.setNickName(userVO.getNickName());
        user.setSource(userVO.getSource());
        user.setUuid(userVO.getUuid());
        user.setQqNumber(userVO.getQqNumber());
        user.setWeChat(userVO.getWeChat());
        user.setOccupation(userVO.getOccupation());
        user.setCommentStatus(userVO.getCommentStatus());
        user.setIpSource(IpUtils.getRealIp(request));
        user.setBrowser(IpUtils.getOsAndBrowserInfo(request).get("BROWSER"));
        user.setOs(IpUtils.getOsAndBrowserInfo(request).get("OS"));
        user.setStartEmailNotification(userVO.getStartEmailNotification());
        user.setUserTag(userVO.getUserTag());
        int i = userDao.insertSelective(user);
        if (i < 1){
            return false;
        }
        //发送验证邮件
        //邮件正文
        String text = "<a href = http://127.0.0.1:8603/login/active?code="+user.getUid()+">请【点击】激活你的账户</a>";
        //给用户发送邮件
        MailUtils.sendMail(user.getEmail(),text,"激活邮件");
        return true;
    }

    @Override
    public Boolean active(String code) {
        User user = userDao.selectByPrimaryKey(code);
        if (user==null){
            return false;
        }
        user.setStatus(1);
        int result = userDao.updateByPrimaryKeySelective(user);
        if (result>0){
            return true;
        }
        return false;
    }
}
